/*
* Copyright 2010 ANDAGO INGENIERIA S.L.
*
* Licensed under the EUPL, Version 1.1 only (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/

package com.andago.alohaui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.andago.bean.Device;
import com.andago.contentProviders.Devices;
import com.andago.contentProviders.Devices.DevicesData;
import com.andago.utils.NomenclatureIEEE;

import es.libresoft.openhealth.android.AgentDevice;
import es.libresoft.openhealth.android.IManagerCallbackService;
import es.libresoft.openhealth.android.IManagerRegister;



public class DevicesActivity extends Activity {	
		
	 // Debugging
    private static final String TAG = "DevicesActivity";
    
	/** The primary interface we will be calling on the service. */
    IManagerRegister mService;    
    
    
    public static HashMap<String, AgentDevice>  listDevices;
    
    
    public static ArrayList<String> listViewDevices;
    public static ArrayList<String> listIDDevices;

    
    private BluetoothAdapter mBtAdapter;
    
    private ListView list;
    
    private Handler handler = new Handler();
    
    private int  attribute_code;
    
    private Context context;
    
    private String device_name;
    private String address_name;
    private String selection;

    
 // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
    
    
 
    private String[] MEASURES = new String[] {
  			"Temperature", 
  			"Weight", 
  			"Oxigen saturation", 
  			"Heart rate",
  			"Glucose"
  			//this.getString(R.string.blood_preassure)
  	    };

    	
    private Runnable doUpdateGUI = new Runnable(){
    	public void run(){
    		
    		updateGUI();
    	}    	
    };

	private ArrayAdapter<String> mNewDevicesArrayAdapter;
	
	private ArrayAdapter<String> mArrayAdapterMeasurements;
	
    
    private void updateGUI(){
    	
    	System.out.println("I'm in updateGUI");
   
    	listViewDevices.clear();
    	listIDDevices.clear();
    	
    	
    	for( Iterator<String> it2 = listDevices.keySet().iterator(); it2.hasNext();) {
    		
    		String key = (String)it2.next();
    		
    		AgentDevice device = listDevices.get(key);
            
	        System.out.println(" Agente SystemId: "+device.getSystemId());
	        System.out.println(" Agente Model: "+device.getModelNumber());
	        System.out.println(" Agente PhID: "+device.getPhdId());
	        System.out.println(" Agente Manufacturar: "+device.getManufacturer());
	        
	        listViewDevices.add(device.getModelNumber() + "-" + device.getManufacturer());
	        listIDDevices.add(device.getSystemId());
	   }   	

    		    	
      	list.setAdapter(new ArrayAdapter<String>(this, R.layout.fila, listViewDevices)); 
    	list.setTextFilterEnabled(true);
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      
      context=this;     
     
      
      listDevices=new HashMap<String, AgentDevice>();
  	  listViewDevices = new ArrayList<String>();
  	  listIDDevices = new ArrayList<String>();

     
      mArrayAdapterMeasurements = new ArrayAdapter<String>(this, R.layout.fila,MEASURES);
      
      mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.fila);
       
       
      
       Bundle extras = getIntent().getExtras();
       if (getIntent().getExtras()!=null){
    	   selection = extras.getString(getString(R.string.selection_bundle));
    	   if (selection.equals(getString(R.string.measures_selection)))
    	   {
    		   	attribute_code = extras.getInt(getString(R.string.measurement_bundle));
    		   	System.out.println("Codigo atributo:" + attribute_code);
    	   }
       }
            
     setContentView(R.layout.listdevices);
     
     list = (ListView) findViewById(R.id.idList);
     
     list.setAdapter(new ArrayAdapter<String>(this, R.layout.fila, listViewDevices)); 
     
     list.setTextFilterEnabled(true);
     
     
     list.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent, View view,
           int position, long id) {
    	   
    	    System.out.println("I'm in onListItemClick "+listViewDevices.size());
    	    System.out.println("I'm in onListItemClick " + listViewDevices.get(position) + " " + id);
    	    
    	    AgentDevice device = listDevices.get(listIDDevices.get(position));
    	    
   			Intent intent = new Intent(DevicesActivity.this, HowtoActivity.class);
   			
   			
   			intent.putExtra("agent", device.getSystemId());
   			intent.putExtra(getString(R.string.selection_bundle), selection);
   			intent.putExtra(getString(R.string.phidDevice_bundle),device.getPhdId());
   			
   			if (selection.equals(getString(R.string.measures_selection)))
   				intent.putExtra(getString(R.string.measurement_bundle), attribute_code);
   			
   			//intent.putExtra(getString(R.string.phidDevice_bundle), devicesphdid.get(position));
   			startActivity(intent);  		
       	

       }
     });
     
     
     /* BT RPO
    //Get the local Bluetooth adapter
     mBtAdapter = BluetoothAdapter.getDefaultAdapter();
     
    //If the adapter is null, then Bluetooth is not supported
     if (mBtAdapter == null) {
         Toast.makeText(this, R.string.bluetooth_not_availabe, Toast.LENGTH_LONG).show();
         finish();
     }

	*/
     
     //to perform device discovery
     Button button_ok = (Button) findViewById(R.id.idbuttom_scan);
     button_ok.setOnClickListener(new OnClickListener() {
         public void onClick(View view) {
        	 doDiscovery();
        	 
        	 //view.setVisibility(View.GONE);       
        	 
        	 
         }
     });


    
     /* BT RPO
     // Register for broadcasts when a device is discovered
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
     this.registerReceiver(mReceiver, filter);

     // Register for broadcasts when discovery has finished
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
     this.registerReceiver(mReceiver, filter);
     
     */
	    // ***************************************************
	    // binding to the service
	    // ***************************************************
     
  
     
     mNewDevicesArrayAdapter.add("DEVICE1" + "\n" + "12345678912345678");
     mNewDevicesArrayAdapter.add("DEVICE2" + "\n" + "12345678912345678");
     mNewDevicesArrayAdapter.add("DEVICE3" + "\n" + "12345678912345678");
     mNewDevicesArrayAdapter.add("DEVICE4" + "\n" + "12345678912345678");
     
     

     bindService(new Intent(IManagerRegister.class.getName()),
  			mConnection, Context.BIND_AUTO_CREATE);
    }

    
    
    protected void doDiscovery() {
    	
		// TODO Auto-generated method stub
    	Log.d(TAG, "doDiscovery()");

        
        /* BT RPO
        
        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
        
        */
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);  
        
        builder.setTitle(R.string.choose_device);
   
        builder.setAdapter(mNewDevicesArrayAdapter,new DialogInterface.OnClickListener() {
        	

			public void onClick(DialogInterface dialog, int item) {
        		
        		/* BT RPO
        		// Cancel discovery because it's costly and we're about to connect
                mBtAdapter.cancelDiscovery();
                
                */
                
               //Get the device MAC address, which is the last 17 chars in the View
                String info = mNewDevicesArrayAdapter.getItem(item);
                device_name = info.substring(0,(info.length() - 17));
                address_name = info.substring(info.length() - 17);
                
                
                
                Log.d(TAG, "device: "+device_name);
                Log.d(TAG, "address: "+address_name);
                
                
                AlertDialog.Builder dialogMeasurement = new AlertDialog.Builder(context);  
                
                dialogMeasurement.setTitle(R.string.choose_measurement);
           
                dialogMeasurement.setMultiChoiceItems(MEASURES, null, new DialogInterface.OnMultiChoiceClickListener() {
                	public void OnMultiChoiceClickListener(DialogInterface dialog, int item,boolean isChecked) {
                	                		
                		
                		
                		String variable = mArrayAdapterMeasurements.getItem(item);
                		
                		Device device = new Device(variable, device_name, address_name);
                		insertIntoDB(device);
                		
                	}

					@Override
					public void onClick(DialogInterface dialog, int which,
							boolean isChecked) {
						// TODO Auto-generated method stub
						
					}
                });
                
                
                AlertDialog alert = dialogMeasurement.create();
                alert.show();
                
               /* BT RPO 
             // Get the BLuetoothDevice object
                BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
                
             // Attempt to connect to the device
                */
                
        	}
        });
        
        AlertDialog alert = builder.create();
        alert.show();
        
        
	}



	private IManagerCallbackService mCallback = new IManagerCallbackService.Stub() {

		/*
		public void agentConnection(String system_id) throws RemoteException {
			// TODO Auto-generated method stub
			System.out.println("I'm in agentConnection!!!!");
		
			devices.add(system_id);
			handler.post(doUpdateGUI);
			
		}*/

		public void agentDisconnection(String system_id) throws RemoteException {
			// TODO Auto-generated method stub
			System.out.println("I'm in agentDisconnection!!!!");
			
			listDevices.remove(system_id);
			
			// devices.remove(system_id);
			
			handler.post(doUpdateGUI);
			
		}
        /**
         * This is called by the remote service regularly to tell us about
         * new values.  Note that IPC calls are dispatched through a thread
         * pool running in each process, so the code executing here will
         * NOT be running in our main thread like most other things -- so,
         * to update the UI, we need to use a Handler to hop over there.
         */

		@Override
		public void agentConnection(AgentDevice agent) throws RemoteException {
			// TODO Auto-generated method stub
			System.out.println("I'm in agentConnection!!!!");
			
			
			System.out.println("Modelo: "+agent.getModelNumber());
			System.out.println("PhID: "+agent.getPhdId());
			
			
			listDevices.put(agent.getSystemId(), agent);			
					
			System.out.println("Añadido Agente ");
			
			/*
			devices.add(agent.getSystemId());	
			
			devicesphdid.add(agent.getPhdId());							
			*/
			
			handler.post(doUpdateGUI);
			
			
		}


    };
    
    private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder service) {			
			// TODO Auto-generated method stub
			System.out.println("I'm in onServiceConnected");
			
			mService = IManagerRegister.Stub.asInterface(service);
						
			try {
				mService.registerCallback(mCallback);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			   // This is called when the connection with the service has been
	          // unexpectedly disconnected -- that is, its process crashed.
			  System.out.println("I'm in ServiceDisconnected");	
	          mService = null;
			
		}
    
    };
    
    private void stopingService (){
    	// Cancel a previous call to startService().  Note that the
        // service will not actually stop at this point if there are
        // still bound clients.
        stopService(new Intent(getString(R.string.droidEvent)));
    	
    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		System.err.println("I'm in onDestroy devicesActivity");
		
		try {
			mService.unregisterCallback(mCallback);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Detach our existing connection.
		unbindService(mConnection);
		System.err.println("devicesActivity: stopping services");
		stopingService();
		super.onDestroy();
	}

	//@Override
	//protected void onPause() {
		// TODO Auto-generated method stub		
	//	System.err.println("I'm in onPause devicesActivity");
		
	//	try {
	//		mService.unregisterCallback(mCallback);
	//	} catch (RemoteException e) {
			// TODO Auto-generated catch block
	//		e.printStackTrace();
	//	}

	//	super.onPause();
	//}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
               // setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                   // String noDevices = getResources().getText(R.string.none_found).toString();
                   // mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };
    
    private void insertIntoDB(Device m){
    	
    	ContentValues values = new ContentValues();				
    	
    	values.put(Devices.DevicesData.VAR_NAME, m.getVariable());
    	values.put(Devices.DevicesData.DEVICE_NAME, m.getDevice_name());
    	values.put(Devices.DevicesData.ADDRESS_NAME, m.getAddress_name());
    	values.put(Devices.DevicesData.DATE, m.getDate());		
    	
    	
    	Uri mURI=getContentResolver().insert(DevicesData.CONTENT_URI, values);
    	if (mURI == null){
    		Log.e("BD", "Failed to insert a new test result into "+ getIntent().getDataString());
    		Toast.makeText(getApplicationContext(), R.string.failled_BD, Toast.LENGTH_SHORT).show();
    		finish();
    		return;
    	}
    	
    }
    
    
    @Override
	public void onStop(){
		super.onStop();
		this.finish();
	}
}
    
